package org.lemon.springmysqltest.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lemon.springmysqltest.entity.Order;
import org.lemon.springmysqltest.service.OrderService;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author : Lemon
 * @date : 2025-05-21 22:18
 **/
@Slf4j
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    @PostMapping
    public ResponseEntity<Order> createOrder(@RequestBody Order order) {
        return ResponseEntity.ok(orderService.createOrder(order));
    }

    @GetMapping("/{id}")
    public ResponseEntity<Order> getOrderById(@PathVariable Long id) {
        return orderService.getOrderById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping
    public ResponseEntity<List<Order>> getAllOrders() {
        return ResponseEntity.ok(orderService.getAllOrders());
    }

    @PutMapping("/{id}")
    public ResponseEntity<Order> updateOrder(@PathVariable Long id, @RequestBody Order order) {
        return ResponseEntity.ok(orderService.updateOrder(id, order));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOrder(@PathVariable Long id) {
        orderService.deleteOrder(id);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/adjust-a")
    public ResponseEntity<Order> adjustA() throws InterruptedException {
        log.info("方法A开始执行 -----------------------》");
        try {
            return ResponseEntity.ok(orderService.adjustOrderA());
        } catch (ObjectOptimisticLockingFailureException e) {
            log.error("订单数据已被其他人修改，请重试", e);
            throw e;
        } finally {
            log.info("方法A结束执行 -----------------------》");
        }
    }

    @PostMapping("/adjust-b")
    public ResponseEntity<Order> adjustB() {
        log.info("方法B开始执行 -----------------------》");
        try {
            return ResponseEntity.ok(orderService.adjustOrderB());
        } finally {
            log.info("方法B结束执行 -----------------------》");
        }
    }

}
